package org.example.springboot.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import org.example.springboot.entity.User;
import org.example.springboot.exception.ServiceException;
import org.example.springboot.mapper.UserMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor{
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler){
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            token = request.getParameter("token");   //url参数 ?token=xxxx
        }

//        if(handler instanceof HandlerMethod){
//            AuthAccess annotation = ((HandlerMethod)handler).getMethodAnnotation(AuthAccess.class);
//            if(annotation != null){
//                return true;
//            }
//        }

// 401 是权限错误
        if(StrUtil.isBlank(token)){
            throw new ServiceException("401", "请登录");
        }

        String userId;
        try{
            userId = JWT.decode(token).getAudience().get(0); // JWT.decode(token) 解码
        }catch (JWTDecodeException j){
            throw new ServiceException("401","请登录");
        }

        User user = userMapper.selectById(Integer.valueOf(userId));
        if (user == null) {
            throw new ServiceException("401","请登录");
        }
        //通过用户密码加密之后生成一个验证器,与TokenUtils中生成的token中的password加密项一一对应
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try{
            jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            throw new ServiceException("401","请登录");
        }
        return true;
    }
}
